<template>
	<main-content :tableHeight.sync="tableHeight">
		<template slot="content">
			<el-table
				v-loading="loading"
				element-loading-spinner="el-icon-loading"
				border
				size="mini"
				class="small-size-table"
				:data="tableData"
				highlight-current-row
				:header-cell-style="getRowClass"
				:max-height="tableHeight"
			>
				<el-table-column
					prop="businessModel"
					align="center"
					label="业务模式"
					show-overflow-tooltip
				>
					<template slot-scope="scope">
						<span>
							{{
								businessModelMap[scope.row.businessModel] || '-'
							}}
						</span>
					</template>
				</el-table-column>
				<el-table-column
					prop="commissionMode"
					align="center"
					label="分润模式"
					show-overflow-tooltip
				>
					<template slot-scope="scope">
						<span>
							{{
								commissionModeMap[scope.row.commissionMode] ||
								'-'
							}}
						</span>
					</template>
				</el-table-column>
				<el-table-column
					prop="defaultConfig"
					align="center"
					label="默认配置"
					min-width="300"
					show-overflow-tooltip
				>
					<template slot-scope="scope">
						<span>
							{{ handleJudgeTitle(scope.row.defaultConfig) }}
						</span>
					</template>
				</el-table-column>
				<el-table-column
					prop="updatedBy"
					align="center"
					label="操作人"
					show-overflow-tooltip
				>
					<template slot-scope="scope">
						<span>{{ scope.row.updatedBy || '-' }}</span>
					</template>
				</el-table-column>

				<el-table-column
					prop="updatedAt"
					align="center"
					label="最后操作时间"
					show-overflow-tooltip
				>
					<template slot-scope="scope">
						<span>{{ scope.row.updatedAt || '-' }}</span>
					</template>
				</el-table-column>
				<el-table-column align="center" label="操作">
					<template slot-scope="scope">
						<el-button
							type="primary"
							size="medium"
							:loading="scope.row.loading"
							@click="handleEdit(scope.row)"
							v-if="hasPermission('90720043')"
						>
							{{ $t('common.edit') }}
						</el-button>
					</template>
				</el-table-column>
			</el-table>
		</template>
		<el-dialog
			title="编辑"
			:visible.sync="dialogFormVisible"
			:close-on-click-modal="false"
			:destroy-on-close="true"
			width="500px"
			center
			@close="resetForm('ruleForm')"
		>
			<el-form
				ref="ruleForm"
				:model="ruleForm"
				:rules="rules"
				label-width="100px"
				label-suffix=":"
				v-loading="detailLoading"
				element-loading-spinner="el-icon-loading"
			>
				<el-form-item label="业务模式" prop="businessModel">
					<el-select
						v-model="ruleForm.businessModel"
						clearable
						disabled
						placeholder="请选择业务模式"
					>
						<el-option
							v-for="(item, index) in businessModelList"
							:key="index"
							:label="item.label"
							:value="item.value"
						></el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="分润模式" required>
					<el-select
						v-model="ruleForm.commissionMode"
						clearable
						disabled
						placeholder=""
					>
						<el-option
							v-for="(item, index) in commissionModeList"
							:key="index"
							:label="item.label"
							:value="item.value"
						></el-option>
					</el-select>
				</el-form-item>
				<div v-if="ruleForm.defaultConfig.length">
					<el-form-item
						v-for="(item, index) in ruleForm.defaultConfig"
						:label="index + 1 + ''"
						:key="index"
						:prop="'defaultConfig.' + index + '.code'"
						:rules="{
							required: true,
							message: '请选择',
							trigger: 'change'
						}"
					>
						<el-select
							v-model="item.code"
							clearable
							placeholder="请选择"
						>
							<el-option
								v-for="(item1, index1) in judgeConfigList(
									item.code
								)"
								:key="index1"
								:label="item1.title"
								:value="item1.code"
							></el-option>
						</el-select>
					</el-form-item>
				</div>
				<el-form-item>
					<el-button
						type="primary"
						:loading="submitBtnLoading"
						@click="submitForm('ruleForm')"
					>
						提交
					</el-button>
				</el-form-item>
			</el-form>
		</el-dialog>
	</main-content>
</template>

<script>
import { routerNames } from '@/utils/consts'
import MainContent from '@/components/MainContent/index.vue'
import list from '@/mixins/list'
import { allConfigList } from './allConfigList'

export default {
  name: routerNames.proxyAppDefaultConfig,
  components: { MainContent },
  mixins: [list],
  data() {
    return {
      allConfigList,
      id: '',
      loading: false,
      detailLoading: false,
      submitBtnLoading: false,
      tableHeight: 480,
      dialogFormVisible: false,
      ruleForm: {
        businessModel: '',
        commissionMode: '',
        defaultConfig: []
      },
      rules: {
        businessModel: [
          { required: true, message: '请选择业务模式', trigger: 'change' }
        ]
      },
      tableData: [],
      businessModelList: [
        {
          label: '现金模式', value: 1
        },
        {
          label: '信用模式', value: 2
        }
      ],
      businessModelMap: {
        1: '现金模式',
        2: '信用模式'
      },
      commissionModeList: [
        {
          label: '占成模式', value: 1
        },
        {
          label: '佣金模式', value: 2
        },
        {
          label: '-', value: null
        }
      ],
      commissionModeMap: {
        1: '占成模式',
        2: '佣金模式'
      }
    }
  },
  methods: {
    handleJudgeTitle(val) {
      return val &&
        JSON.parse(val)?.length
        ? JSON.parse(val)
          .map((item) => item.title)
          .join('、')
        : '-'
    },
    loadData() {
      this.loading = true
      this.$api.getAppDefaultConfigList({}).then(res => {
        this.tableData = res.data || []
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    judgeConfigList(val) {
      return this.allConfigList.filter(item => {
        const index = this.ruleForm.defaultConfig.findIndex(item1 => item1.code === item.code)
        return (this.ruleForm.businessModel == 1 ? item.hasCash : item.hasCredit) && (index === -1 || (index !== -1 && item.code === val)) && (this.ruleForm.businessModel == 1 ? (this.ruleForm.commissionMode == 1 ? item.hasZhancheng : item.hasRebate) : true)
      })
    },
    getDetail(val) {
      this.detailLoading = true
      val.loading = true
      this.$api.getAppDefaultConfigDetail({ id: val.id }).then(res => {
        this.ruleForm.businessModel = res.data.businessModel
        this.ruleForm.commissionMode = res.data.commissionMode
        this.ruleForm.defaultConfig = res.data.defaultConfig ? JSON.parse(res.data.defaultConfig) : []
        this.detailLoading = false
      }).finally(() => {
        this.detailLoading = false
        val.loading = false
      })
    },
    handleEdit(val) {
      this.$set(val, 'loading', false)
      this.id = val.id
      this.getDetail(val)
      this.dialogFormVisible = true
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.$confirm('确认修改APP代理中心常用功能配置？', '', {
            confirmButtonText: '确定',
            cancelButtonText: '取消'
          }).then(() => {
            this.submitBtnLoading = true
            this.$api.updateAppDefaultConfig({
              id: this.id,
              businessModel: this.ruleForm.businessModel,
              commissionMode: this.ruleForm.commissionMode,
              defaultConfig: JSON.stringify(this.ruleForm.defaultConfig.map(item => {
                this.allConfigList.map(item1 => {
                  if (item1.code === item.code) {
                    item.title = item1.title
                    item.iconName = item1.iconName
                  }
                })
                return item
              }))
            }).then(() => {
              this.$message({
                type: 'success',
                message: '操作成功!'
              })
              this.dialogFormVisible = false
              this.loadData()
            }).finally(() => {
              this.submitBtnLoading = false
            })
          }).catch(() => {
            this.$message({
              type: 'info',
              message: '已取消'
            })
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
      this.dialogFormVisible = false
    }
  }
}
</script>

<style lang="scss" scoped>
::v-deep .params {
	padding: 0;
}
</style>
